package com.ming.reggie.controller;

import com.ming.reggie.common.R;
import com.ming.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String baseDir;

//springmvc文件上传要求
//要求1:必须使用MultipartFile类型接收上传文件对象
//要求2: MultipartFile类型参数名字必须与前端文件域表单元素name属性值一样,如果不一样需要使用@RequestParam("别名")
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1.获取上传文件的文件名
        String filename = file.getOriginalFilename();

        //获取文件扩展名
        String fileExtName = filename.substring(filename.lastIndexOf("."));//.jpg

        //创建唯一随机的新的文件名
        String newFileName = UUIDUtils.getUUID() + fileExtName;

        //2.将文件保存到path路径目录下
        File dir = new File(baseDir);
        if(!dir.exists()){
            //没有当前目录就生成
            dir.mkdir();
        }

        //进行保存
        file.transferTo(new File(baseDir + newFileName));

        return R.success(newFileName);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {

        //输入流
        FileInputStream inputStream = new FileInputStream(baseDir + fileName);

        //输出流
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(inputStream,outputStream);


    }
}
